package com.swak.vertx.protocol.http.adapter;

import java.util.concurrent.CompletionStage;
import java.util.function.BiConsumer;

import com.swak.utils.StringUtils;

import io.vertx.core.http.HttpHeaders;

/**
 * 开启指标记录
 * 
 * @author lifeng
 */
public class MetricsAdapter extends AbstractAdapter {

	private final BiConsumer<Context, Throwable> handle;

	public MetricsAdapter() {
		this.handle = this::handle;
	}

	@Override
	public CompletionStage<Context> handle(Context context) {
		context.$metric = context.$method.metrics != null ? context.$method.metrics.begin() : null;
		CompletionStage<Context> nextFuture = this.next(context);
		nextFuture.whenComplete(this.handle);
		return nextFuture;
	}

	@SuppressWarnings("unchecked")
	protected void handle(Context context, Throwable error) {
		if (context.$method.metrics != null) {
			String value = context.$context.response().headers().get(HttpHeaders.CONTENT_LENGTH);
			long outputSize = StringUtils.isBlank(value) ? 0 : Long.parseLong(value);
			context.$method.metrics.end(context.$metric, outputSize, error == null);
		}
	}

}